package com.lock.demo.redis.lock;

import com.lock.demo.mysql.entity.LockRecord;
import com.lock.demo.mysql.mapper.LockMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @ProjectName: lock_demo
 * @Package: com.lock.demo.mysql.lock
 * @Author: huat
 * @Date: 2021/5/4 14:03
 * @Version: 1.0
 */
@Component
public class RedisLock implements Lock {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    private final static String LOCK_NAME="lockName";


    /**
     * 上锁
     */
    @Override
    public void lock() {
        while (true){
            boolean result = redisTemplate.opsForValue().setIfAbsent(LOCK_NAME,LOCK_NAME);
            //设置过期时间
            result=redisTemplate.expire(LOCK_NAME,15,TimeUnit.SECONDS);
            if (result){
                return ;
            }

        }
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    /**
     * 尝试获取锁：根据数据库名称发起一次查询
     * sql：select id,lock_name from lock_record where lock_name="自定义锁形成"
     * @return
     */
    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {

        return false;
    }

    /**
     * 解锁
     * 本质就是删除锁记录
     */
    @Override
    public void unlock() {
        redisTemplate.delete(LOCK_NAME);
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
